import { concat, find, pluck, propEq, uniq } from "ramda";
import { create } from "zustand";

interface Product {
  id: string;
  name: string;
  couple: string[];
}

interface ProductsStore {
  products: Product[];
  selectedProducts: string[];
  append: (code: string) => void;
  remove: (code: string) => void;
  unselectAll: () => void;
  selectAll: () => void;
}

export const useProductsStore = create<ProductsStore>((set, get) => ({
  products: [],
  selectedProducts: [],
  append: (code: string) => {
    const selectedProduct: Product | undefined = find(propEq(code, "id"), get().products);
    set((state) => ({
      selectedProducts: uniq([...state.selectedProducts, code, ...(selectedProduct?.couple ?? [])]),
    }));
  },
  remove: (code: string) =>
    set((state) => ({ selectedProducts: state.selectedProducts.filter((item) => item !== code) })),
  unselectAll: () => set({ selectedProducts: [] }),
  selectAll: () => {
    const products = pluck("id", get().products);
    const selectedProducts = uniq(concat(get().selectedProducts, products));
    set({ selectedProducts: selectedProducts });
  },
}));
